<template>
    <div class="wrap">
        <swiper ref="swiperRef" :centeredSlides="true" :spaceBetween="10" :speed="7000"
            :slidesPerView="slidesPerViewNum" :autoplay="{
                delay: 10,
                disableOnInteraction: false,
                autopalyDisableOnInteraction: false
            }" :modules="modules" :loop="true" :style="`width:${infoData.Resolutionwidth}px;`" class="swiperBox">
            <swiper-slide v-for="(item, index) in infoData.images" :key="index" class="swipper-slide">
                <img :src="item" class="swiper-image" v-if="infoData.isMaterialImg" />
                <video id="videoBox" class="video-wrap" controls autoplay loop :src="item"
                    v-if="infoData.isMaterialVideo">
                </video>
            </swiper-slide>
        </swiper>
        <img :src="infoData.BackgroundImageShow" class="wrap_bg video_bg" v-if="infoData.isBackImg" />

        <audio class="audio_wrap" :src="`${infoData.backgroundMusic}`" controls autoplay loop>
            <!-- <source :src="`${baseUrl}/${infoData.backgroundMusic}`"  type="audio/mp3"> -->
        </audio>
        <video class="video_bg" id="video_bg_box" :src="infoData.BackgroundImageShow" autoplay loop preload="auto"  :poster="poster"
            v-if="!infoData.isBackImg">
        </video>
    </div>
</template>
<script setup name="swipercomp">
import axios, { baseUrl } from '../utils/http'
import { checkImgExists, checkVideoExists, checkAudioExists } from '../utils/util'
import { ref, onMounted, watch } from 'vue'
// import Swiper JS
import { Swiper, SwiperSlide } from 'swiper/vue';
// import { Autoplay, EffectCoverflow } from 'swiper/modules';
import { Autoplay, Scrollbar } from 'swiper/modules'
import 'swiper/css';
// import 'swiper/css/navigation';
// import Swiper styles
import 'swiper/css';
//import poster from '@/assets/img/grey.png'

const img1 = 'http://124.221.137.201:8081/Upload/Tables/SZ_CeremonyTemplate/202410051716048369/风景1908002.jpg'
const img2 = 'https://swiperjs.com/demos/images/nature-1.jpg'
const img3 = 'https://swiperjs.com/demos/images/nature-3.jpg'

const slidesPerViewNum = ref(5);
const originH = ref(100);
const originW = ref(100);
const heightRef = ref(0)
const infoData = ref({})
const photoH = ref(472)
const swiperRef = ref(null)
const poster = ref('');

const props = defineProps({
    data: {
        type: Object,
        default: () => { }
    }
})

/**
 * 从视频中抓取第一帧，生成 base64 poster
 * @param {String} src 视频 URL
 * @returns {Promise<String>} Promise resolves to dataURL
 */
 function captureFirstFrame(src) {
  return new Promise((resolve, reject) => {
    const vid = document.createElement('video')
    vid.crossOrigin = 'anonymous'   // 如果是跨域资源，需要服务端允许 CORS
    vid.src = src
    vid.preload = 'metadata'
    vid.muted = true                // 某些浏览器需要静音才能 autoplay/seek

    // 1. metadata 加载后可以拿到 videoWidth/videoHeight
    vid.addEventListener('loadedmetadata', () => {
      // 有些视频第一帧可能是全黑，跳到 0.1s 更保险
      vid.currentTime = 0.1
    })

    // 2. 跳帧完成后，把这一帧画到 canvas
    vid.addEventListener('seeked', () => {
      const w = vid.videoWidth
      const h = vid.videoHeight
      const canvas = document.createElement('canvas')
      canvas.width  = w
      canvas.height = h
      const ctx = canvas.getContext('2d')
      ctx.drawImage(vid, 0, 0, w, h)
      // 3. 导出 base64
      try {
        const dataURL = canvas.toDataURL('image/png')
        resolve(dataURL)
      } catch (err) {
        reject(err)
      }
    })

    // 错误处理
    vid.addEventListener('error', e => {
      reject(new Error('视频加载失败'))
    })
  })
 }



//console.log('photo-watch-init', props.data)

//const modules = [Autoplay, EffectCoverflow] // [Autoplay, EffectCoverflow]
const modules = [Autoplay]

const imagesTest = ref([

    img1, img2, img3, img1
])


const handleSlideChange = (swiper) => {

    //console.log('当前激活的幻灯片索引:', swiper);
}

const handleswiper = (s) => {
    // console.log('handleswiper',s)
}
const setInitImgfn = (imageUrl) => {
    var img = new Image();
    img.src = imageUrl;

    // 当图片加载完成时获取其尺寸
    img.onload = function () {
        var width = img.width;
        var height = img.height;
        originW.value = width;
        originH.value = height;
    };

    // 错误处理
    img.onerror = function () {
        //document.getElementById('sizeInfo').innerText = 'Failed to load background image.';
    };
}


const config = import.meta.env.VITE_PACKAGE_CONFIG;
watch(() => props.data, async (val,newval) => {

    if (Object.keys(val).length) {
        const obj = { ...val };
        const numFile = obj.CeremonyOrdersID;

        const bgMater = numFile + '/' + obj.BackgroundImage;
        const mater = numFile + '/' + obj.BackgroundMaterial;
        const music = numFile + '/' + obj.backgroundMusic;
        const bgMater_online = baseUrl + '/' + obj.BackgroundImage;
        const mater_online = obj.BackgroundMaterial ? baseUrl + '/' + obj.BackgroundMaterial : '';
        const music_online = obj.backgroundMusic ? baseUrl + '/' + obj.backgroundMusic : ''
        if (config == 'online') {
            obj.BackgroundImageShow = bgMater_online;
            obj.backgroundMusic = music_online

        } else {
            // if (obj.isBackVideo || obj.isBackImg) {
            //     let bgRes = null;
            //     if (obj.isBackVideo) {
            //         bgRes = await checkVideoExists(bgMater)
            //     }
            //     if (obj.isBackImg) {
            //         bgRes = await checkImgExists(bgMater)
            //     }
            //     if (!bgRes) {
            //         obj.BackgroundImageShow = bgMater_online;
            //     } else {
            //         obj.BackgroundImageShow = bgMater;
            //     }
            // }

            // const music_on = await checkAudioExists(music);

            // if (music_on) {
            //     obj.backgroundMusic = music;
            // } else {
            //     obj.backgroundMusic = music_online
            // }
            poster.value = `${obj.BackgroundImageLocal?.split('.mp4')?.[0]}.jpg`
            obj.BackgroundImageShow = obj.BackgroundImageLocal;
            obj.backgroundMusic = obj.backgroundMusicLocal;
        }

        let rImg = []
        if (obj.BackgroundMaterial) {
            let images = []
            if (config == 'online') {
                images = obj.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (baseUrl + '/' + v))
            } else {
                // if (obj.isMaterialImg || obj.isMaterialVideo) {
                //     let mRes = null;
                //     if (obj.isMaterialVideo) {
                //         mRes = await checkVideoExists(mater)
                //     }
                //     if (obj.isMaterialImg) {
                //         mRes = await checkImgExists(mater)
                //     }
                //     if (!mRes) {
                //         images = obj.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (baseUrl + '/' + v))

                //     } else {
                //         images = obj.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (numFile + '/' + v))
                //     }
                // }
                images = obj.BackgroundMaterialLocal
                //images = obj.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (numFile + '/' + v))
            }
            rImg = [...images];
            slidesPerViewNum.value = rImg.length;
        }

        //console.log('swiperobj', obj)
        infoData.value = { ...obj, images: rImg };
    }
}, {
    deep: true,
    immediate: true
})



onMounted(() => {


})


</script>
<style lang="less" scoped>
.wrap {
    position: relative;
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

.swiperBox {

    //     .swiper-slide {
    //         background-position: center;
    //         background-size: cover;
    //         width: 300px;
    //         // height: 300px;
    //         /* Center slide text vertically */
    //         display: -webkit-box;
    //         display: -ms-flexbox;
    //         display: -webkit-flex;
    //         display: flex;
    //         -webkit-box-pack: center;
    //         -ms-flex-pack: center;
    //         -webkit-justify-content: center;
    //         justify-content: center;
    //         -webkit-box-align: center;
    //         -ms-flex-align: center;
    //         -webkit-align-items: center;
    //         align-items: center;
    //         transition: 300ms;
    //         transform: scale(0.8);
    //   }
    height: 100vh;

    :deep(.swiper-wrapper) {
        -webkit-transition-timing-function: linear !important;
        -moz-transition-timing-function: linear !important;
        -ms-transition-timing-function: linear !important;
        -o-transition-timing-function: linear !important;
        transition-timing-function: linear !important;
    }


    .swiper-slide {
        display: flex;
        align-items: center;
        justify-content: center;

        .swiper-image {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: scale-down;
        }
    }
}




// :deep(.swiper-horizontal) {
//     height:472px;
// }

// .swiper-slide-active,
// .swiper-slide-duplicate-active {
//     transform: scale(1);
// }

.video_bg {
    position: absolute;
    left: 0;
    top: 0;
    //   width: 100vw;
    //   height: 100%;
    z-index: -2;
    //object-fit: cover; /* 确保视频填满屏幕，且保持视频比例 */
    background-color: transparent;
    /* 背景颜色，避免视频比例问题时的黑边 */
}

.audio_wrap {
    margin: 30px 0 0 0;
    opacity: 0;
    display: none;
}
</style>